package cn.ym.ymcc.mq;

import cn.ym.ymcc.constant.CustomConstant;
import cn.ym.ymcc.domain.MessageStation;
import cn.ym.ymcc.dto.MessageStationDto;
import cn.ym.ymcc.mapper.MessageStationMapper;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
@RocketMQMessageListener(topic = CustomConstant.MQ_TOPIC_MESSAGE_STATION,
        selectorExpression = CustomConstant.MQ_TAGS_MESSAGE_STATION,
    consumerGroup = "service-message-station-consumer")
public class MessageStationConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private MessageStationMapper messageStationMapper;

    @Override
    public void onMessage(MessageExt messageExt) {
        //1.获取消息
        byte[] body = messageExt.getBody();
        //2.将消息转化成字符串
        String jsonData = new String(body, StandardCharsets.UTF_8);
        //3.把json字符串转为对象
        MessageStationDto messageStationDto = JSONObject.parseObject(jsonData, MessageStationDto.class);

        //发送站内信
        sendMessageStation(messageStationDto);
    }

    /**
     * 发送站内信
     * @param messageStationDto
     */
    private void sendMessageStation(MessageStationDto messageStationDto) {
        List<Long> userIds = messageStationDto.getUserIds();
        for (Long userId : userIds) {
            MessageStation messageStation = new MessageStation();
            BeanUtils.copyProperties(messageStationDto, messageStation);
            messageStation.setUserId(userId);
            messageStation.setSendTime(new Date());
            messageStation.setIsread(0);
            messageStationMapper.insert(messageStation);
            log.info("发送站内信内容为：" + messageStation.getContent());
        }
    }
}
